<template>
  <view class="container">
    <view class="form-group">
      <view class="form-item">
        <text class="label">验证码</text>
        <input type="text" v-model="orderForm.verificationCode" placeholder="请输入验证码" />
      </view>
      
      <view class="form-item">
        <text class="label">服务类型</text>
        <picker @change="onServiceTypeChange" :value="serviceTypeIndex" :range="serviceTypes">
          <view class="picker">
            {{ serviceTypes[serviceTypeIndex] || '请选择服务类型' }}
          </view>
        </picker>
      </view>
      
      <view class="form-item">
        <text class="label">预约时间</text>
        <picker mode="date" :value="orderForm.reservationTime" @change="onDateChange">
          <view class="picker">
            {{ orderForm.reservationTime || '请选择预约日期' }}
          </view>
        </picker>
      </view>
      
      <view class="form-item">
        <text class="label">价格</text>
        <input type="number" v-model="orderForm.price" placeholder="请输入价格" />
      </view>
    </view>
    
    <button class="submit-btn" 
            :class="{ 'disabled': isSubmitted }" 
            :disabled="isSubmitted"
            @click="comfirmOrder">
      {{ isSubmitted ? '已支付' : '提交订单' }}
    </button>
  </view>
</template>

<script>
import request from "../../util/request";
import baseUrl from "../../util/urlConfig";

export default {
  data() {
    return {
      ws: null,
      show: false,
      wsUrl: 'ws://localhost:9407/myws/',  // 确保与商家端使用相同的WebSocket服务器地址
      isSubmitted: false,  // 添加提交状态
      serviceTypeIndex: 0,
      serviceTypes: ['基础保养', '汽车美容', '维修服务'],
      orderForm: {
        verificationCode: '',
        verificationImg: '',
        serviceId: 0,
        mid: 2,
        serviceTypeId: 2,
        orderTime: '',
        reservationTime: '',
        carId: 2,
        couponId: 1,
        price: 0,
        payTime: '',
        status: 2,
        deleted: 0,
        evaluate: 1,
        userId: 12,
        reserved2: ''
      }
    }
  },
  
  onLoad() {
    this.initWebSocket();
  },
  
  onUnload() {
    if (this.ws) {
      uni.closeSocket();
    }
  },
  
  methods: {
    // 建立WebSocket连接
    initWebSocket() {
      try {
        const userId = uni.getStorageSync('user').id;
        if (!userId) {
          console.error('用户ID不存在');
          return;
        }
        
        // 使用uni.connectSocket替代原生WebSocket
        this.ws = uni.connectSocket({
          url: this.wsUrl + userId,
          success: () => {
            console.log('WebSocket连接创建成功');
          },
          fail: (error) => {
            console.error('WebSocket连接创建失败:', error);
          }
        });
        
        // 监听WebSocket连接打开
        uni.onSocketOpen(() => {
          console.log('WebSocket连接已打开');
        });
        
        // 监听WebSocket接收到服务器的消息
        uni.onSocketMessage((res) => {
          console.log('收到服务器内容：', res.data);
        });
        
        // 监听WebSocket错误
        uni.onSocketError((res) => {
          console.error('WebSocket连接错误:', res);
        });
        
        // 监听WebSocket关闭
        uni.onSocketClose((res) => {
          console.log('WebSocket已关闭:', res);
        });
        
      } catch (error) {
        console.error('初始化WebSocket失败:', error);
      }
    },

    // 初始化订单表单
    initOrderForm() {
      const now = new Date();
      this.orderForm.orderTime = this.formatDate(now);
      this.orderForm.payTime = this.formatDate(now);
    },

    // 格式化日期
    formatDate(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },

    // 服务类型选择改变
    onServiceTypeChange(e) {
      this.serviceTypeIndex = e.detail.value;
      this.orderForm.serviceTypeId = this.serviceTypeIndex + 1;
    },

    // 日期选择改变
    onDateChange(e) {
      this.orderForm.reservationTime = e.detail.value;
    },

    // 请求Promise封装
    requestPromise(config) {
      return new Promise((resolve, reject) => {
        request({
          url: config.url,
          method: config.method,
          data: config.data,
          success: resolve,
          fail: reject,
        })
      })
    },

    // 提交订单
    async comfirmOrder() {
      if (this.isSubmitted) return;  // 如果已经提交，直接返回
      
      try {
        // 表单验证
        if (!this.orderForm.verificationCode) {
          uni.showToast({
            title: '请输入验证码',
            icon: 'none'
          });
          return;
        }

        if (!this.orderForm.reservationTime) {
          uni.showToast({
            title: '请选择预约时间',
            icon: 'none'
          });
          return;
        }

        if (!this.orderForm.price) {
          uni.showToast({
            title: '请输入价格',
            icon: 'none'
          });
          return;
        }

        const result = await this.requestPromise({
          url: baseUrl + '/wwc/orders',
          method: 'POST',
          data: this.orderForm
        });

        if (result.data.code === 200) {
          // 获取商家ID
          const merchantId = uni.getStorageSync('merchant').id;
          
          // 发送WebSocket消息
          const message = JSON.stringify({
            type: 'NEW_ORDER',
            orderId: result.data.data.id,
            message: '新订单通知',
            targetId: merchantId,  // 添加目标商家ID
            fromId: uni.getStorageSync('user').id  // 添加发送者ID
          });
          
          console.log('准备发送消息:', message);  // 添加日志
          
          uni.sendSocketMessage({
            data: message,
            success: () => {
              console.log('WebSocket消息发送成功，消息内容:', message);  // 添加日志
            },
            fail: (error) => {
              console.error('WebSocket消息发送失败:', error);
            }
          });

          // 更新按钮状态
          this.isSubmitted = true;

          uni.showToast({
            title: '订单提交成功',
            icon: 'success'
          });

          // 跳转到订单页面
          uni.navigateTo({
            url: '/pages/yonghu1/tijiaodingdan/tijiaodingdan'
          });
        } else {
          uni.showToast({
            title: result.data.msg || '订单提交失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('提交订单失败:', error);
        uni.showToast({
          title: '提交订单失败，请重试',
          icon: 'none'
        });
      }
    }
  }
}
</script>

<style>
.container {
  padding: 20px;
}

.form-group {
  background-color: #fff;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 20px;
}

.form-item {
  margin-bottom: 15px;
}

.label {
  display: block;
  margin-bottom: 5px;
  color: #333;
  font-size: 14px;
}

input {
  width: 100%;
  height: 40px;
  border: 1px solid #ddd;
  border-radius: 4px;
  padding: 0 10px;
  font-size: 14px;
}

.picker {
  width: 100%;
  height: 40px;
  border: 1px solid #ddd;
  border-radius: 4px;
  padding: 0 10px;
  font-size: 14px;
  line-height: 40px;
}

.submit-btn {
  width: 100%;
  height: 44px;
  background-color: #2196F3;
  color: #fff;
  border-radius: 4px;
  font-size: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.submit-btn.disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.submit-btn:active {
  opacity: 0.8;
}
</style> 